package com.by_man.presenter.module_member_activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.by_man.presenter.R;
import com.by_man.presenter.SharedApplication;
import com.by_man.repository.LocalDataManager;
import com.by_man.repository.NetworkDataManager;
import com.by_man.repository.UserInfos;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by man on 2017-02-25.
 */
public class MemberActivityFragment extends Fragment {
    private ProgressDialog progressDialog;
    private View view;
    private Handler handler;
    @Override   //绑定布局
    public View onCreateView(LayoutInflater inflater, ViewGroup container, final Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_member_activity, container, false);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                initView(view);
            }
        };
        if (null == UserInfos.All_New_Activity || null == UserInfos.All_Lately_Activity) {
            progressDialog = new ProgressDialog(getActivity());
            progressDialog.setTitle("提示信息");
            progressDialog.setMessage("正在请求数据，请稍后......");
            progressDialog.setCancelable(false);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.show();

            Thread thread = new Thread() {
                public void run() {
                    while (null == UserInfos.All_New_Activity || null == UserInfos.All_Lately_Activity) {        // 阻塞等待数据的初始化
                        if (NetworkDataManager.NewActivityNum < 1 || NetworkDataManager.LatelyActivityNum < 1) {
                            showRequestAgain();
                        }
                    }
                    progressDialog.dismiss();
                    Message message = Message.obtain(handler);
                    message.sendToTarget();
                }
            };
            thread.setDaemon(true);             // 设置为守护线程
            thread.start();
        } else {
            initView(view);
        }
        return view;
    }

    private void initView(View view) {
        Button btn1 = (Button) view.findViewById(R.id.image1);
        Button btn2 = (Button) view.findViewById(R.id.image2);
        Button btn3 = (Button) view.findViewById(R.id.image3);
        Button btn4 = (Button) view.findViewById(R.id.image4);

        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), ActivityDetailActivity.class);
                intent.putExtra("extra", "page_one");
                startActivity(intent);
            }
        });
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), ActivityDetailActivity.class);
                intent.putExtra("extra", "page_two");
                startActivity(intent);
            }
        });
        btn3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), ActivityDetailActivity.class);
                intent.putExtra("extra", "page_three");
                startActivity(intent);
            }
        });
        btn4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), ActivityDetailActivity.class);
                intent.putExtra("extra", "page_four");
                startActivity(intent);
            }
        });

        final ListView listViewOne = (ListView) view.findViewById(R.id.hd_neirong);
        final ListView listViewTwo = (ListView) view.findViewById(R.id.neirong2);

        listViewOne.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                TextView textView = (TextView) view.findViewById(R.id.list_meeting);
                Intent intent = new Intent(getActivity(), NewsActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.putExtra("extra_data", textView.getText());
                startActivity(intent);
            }
        });

        listViewTwo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                TextView textView = (TextView) view.findViewById(R.id.list_meeting);
                Intent intent = new Intent(getActivity(), LasetedNewsActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.putExtra("extra_data", textView.getText());
                startActivity(intent);
            }
        });

        JSONArray jsonArrayNew = LocalDataManager.getAllNewActivity();
        JSONArray jsonArrayLately = LocalDataManager.getAllLatelyActivity();
        if (null != jsonArrayNew) {
            ArrayList<HashMap<String, String>> items = new ArrayList<HashMap<String, String>>();
            try {
                for (int i = 0; i < jsonArrayNew.length(); i++) {
                    HashMap<String, String> map = new HashMap<String, String>();
                    map.put("meeting", ((JSONObject)jsonArrayNew.get(i)).getString("meeting_name"));
                    items.add(map);
                }
                SimpleAdapter adapter = new SimpleAdapter(getActivity(), items, R.layout.item_listview_member_activity,
                        new String[]{"meeting"}, new int[]{R.id.list_meeting});
                listViewOne.setAdapter(adapter);
            } catch (JSONException je) {
                je.printStackTrace();
            }
        }

        if (null != jsonArrayLately) {
            ArrayList<HashMap<String, String>> items = new ArrayList<HashMap<String, String>>();
            try {
                for (int i = 0; i < jsonArrayLately.length(); i++) {
                    HashMap<String, String> map = new HashMap<String, String>();
                    map.put("meetingend", ((JSONObject)jsonArrayLately.get(i)).getString("title"));
                    items.add(map);
                }
                SimpleAdapter adapter = new SimpleAdapter(getActivity(), items, R.layout.item_listview_member_activity,
                        new String[]{"meetingend"}, new int[]{R.id.list_meeting});
                listViewTwo.setAdapter(adapter);
            } catch (JSONException je) {
                je.printStackTrace();
            }
        }
    }

    public void showRequestAgain() {
        AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).setTitle("提醒")
                .setMessage("已多次请求服务器，是否继续请求？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        NetworkDataManager.NewActivityNum = 3;
                        NetworkDataManager.LatelyActivityNum = 3;
                        LocalDataManager.getAllNewActivity();
                        LocalDataManager.getAllLatelyActivity();
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                }).create();
        alertDialog.show();
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }
}
